package com.example.testsbjenkins.DynamicProxyAndReflex;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: lt
 * @date: 2022/7/6 18:06
 * @Description: 测试动态代理实现 方法调用
 */
public class MyDynamicProxy {

    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);

        UserService service = (UserService) Proxy.newProxyInstance(UserServiceImpl.class.getClassLoader(), UserServiceImpl.class.getInterfaces(), invocationHandler);
        service.sayHello("world");
    }
    
    
    
    interface UserService{
        void sayHello(String name);
    }
    
    static class UserServiceImpl implements UserService {

        @Override
        public void sayHello(String name) {
            System.out.println("hello "+name);
        }
    }
    
    
    static class MyInvocationHandler implements InvocationHandler {
        
        private Object object;

        public MyInvocationHandler(Object object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("调用目标方法之前");
            Object result = method.invoke(object, args);
            System.out.println("调用目标方法之后");
            return result;
        }
    }
}
